<template>
  <BasePage>
    <MyTable
      ref="$table"
      :columns="columns"
      :query-schemas="querySchemas"
      :get-data="userApi.list"
      :index="true"
    >
      <template #handle>
        <AddButton @click="handleAdd">添加用户</AddButton>
      </template>
    </MyTable>
    <MyForm ref="$form" :model-form="model" @submit="handleSubmit">
      <template v-if="!model.isReset">
        <n-form-item label="账号" path="username" :rule="{ required: true, message: '请输入账号' }">
          <n-input v-model:value="model.username" maxlength="50" clearable show-count />
        </n-form-item>
        <n-form-item
          label="手机号"
          path="phone"
          :rule="[
            {
              required: true,
              message: '请输入手机号',
            },
            { validator: validatorPhone('手机号格式错误！') },
          ]"
        >
          <n-input
            v-model:value="model.phone"
            clearable
            maxlength="11"
            :allow-input="(value) => !value || /^\d+$/.test(value)"
          />
        </n-form-item>
        <n-form-item label="姓名" path="name" :rule="{ required: true, message: '请输入姓名' }">
          <n-input v-model:value="model.name" maxlength="50" clearable />
        </n-form-item>
        <n-form-item label="性别" path="gender" :rule="{ required: true, message: '请选择性别' }">
          <n-radio-group v-model:value="model.gender">
            <n-radio :value="1">男</n-radio>
            <n-radio :value="0">女</n-radio>
          </n-radio-group>
        </n-form-item>
        <n-form-item
          label="绑定部门"
          path="deptId"
          :rule="{ required: true, message: '请选择绑定部门' }"
        >
          <n-cascader
            v-model:value="model.deptId"
            :options="deptTree"
            clearable
            filterable
            value-field="id"
          />
        </n-form-item>
        <n-form-item label="职务" path="office" :rule="{ required: true, message: '请输入职务' }">
          <n-input v-model:value="model.office" maxlength="50" clearable />
        </n-form-item>
        <n-form-item
          label="绑定角色"
          path="roleId"
          :rule="{ required: true, message: '请选择绑定角色' }"
        >
          <AsyncSelect
            v-model:value="model.roleId"
            :options="roleApi.listAll"
            label-key="name"
            value-key="id"
          />
        </n-form-item>
      </template>

      <n-form-item
        v-if="type === 'add' || model.isReset"
        label="登录密码"
        path="password"
        :rule="{ required: true, message: '请输入登录密码' }"
      >
        <n-input
          v-model:value="model.password"
          type="password"
          show-password-on="click"
          :input-props="{ autoComplete: 'new-password' }"
        />
      </n-form-item>
      <n-form-item
        v-if="type === 'add'"
        label="确认密码"
        path="repeatPassword"
        :rule="[
          { required: true, message: '请输入确认密码' },
          { validator: validatorConfirmPassword(model.password, '确认密码与登录密码不一致') },
        ]"
      >
        <n-input
          v-model:value="model.repeatPassword"
          type="password"
          show-password-on="click"
          :input-props="{ autoComplete: 'new-password' }"
        />
      </n-form-item>
      <!-- 头像 -->
    </MyForm>
  </BasePage>
</template>
<script setup lang="jsx">
defineOptions({ name: 'UserManage' })
import * as userApi from '@/api/user'
import * as roleApi from '@/api/role'
import * as deptApi from '@/api/dept'
import { useCrud } from '@/hooks/useCrud'
import { validatorPhone, validatorConfirmPassword } from '@/utils/ruls'
import { onBeforeMount } from 'vue'
const querySchemas = [
  {
    field: 'name',
    component: 'NInput',
    componentProps: {
      placeholder: '账号手机/姓名',
    },
  },
  {
    field: 'roleId',
    component: 'AsyncSelect',
    componentProps: {
      placeholder: '请选择角色',
      options: roleApi.listAll,
      labelKey: 'name',
      valueKey: 'id',
    },
  },
]
const columns = [
  {
    title: '账号',
    key: 'username',
  },
  {
    title: '手机号',
    key: 'phone',
  },
  {
    title: '姓名',
    key: 'name',
  },
  {
    title: '性别',
    key: 'gender',
    render: ({ gender }) => ['女', '男']?.[gender] || '--',
  },
  {
    title: '角色',
    key: 'roleName',
  },
  {
    title: '部门',
    key: 'deptName',
  },
  {
    title: '职务',
    key: 'office',
  },
  {
    title: '状态',
    key: 'status',
  },
  {
    title: '创建时间',
    key: 'createTime',
  },
  {
    title: '操作',
    key: 'actions',
    width: 240,
    align: 'left',
    fixed: 'right',
    hideInExcel: true,
    render(row) {
      return (
        <n-flex>
          <ActionButton onClick={() => handleReset(row)}>重置密码</ActionButton>
          <ActionButton onClick={() => handleEdit(row)}>修改</ActionButton>
          <ActionButton onClick={() => handleDel(row)}>删除</ActionButton>
        </n-flex>
      )
    },
  },
]
function handleReset(row) {
  handleEdit(row, {
    title: '重置密码',
    onShow: () => {
      model.value.isReset = true
    },
  })
}
const { type, model, $form, $table, isView, handleAdd, handleEdit, handleDel, handleSubmit } =
  useCrud({
    name: '用户',
    initForm: {
      id: null,
      username: null,
      phone: null,
      name: null,
      gender: 1,
      deptId: null,
      office: null,
      roleId: null,
      password: null,
      repeatPassword: null,
      avatar: null,
      isReset: false,
    },
    apis: {
      add: userApi.add,
      edit: (params) => {
        return model.value.isReset ? userApi.resetPassword(params) : userApi.edit(params)
      },
      del: ({ id }) => userApi.del(id),
      view: ({ id }) => userApi.info(id).then((res) => res.data),
    },
    customChange: (_, defaultHandle) => {
      if (model.value.isReset) {
        $message.success(`重置密码成功!`)
        $table?.value?.handleQuery()
      } else {
        defaultHandle()
      }
    },
  })

const deptTree = ref([])
async function getDeptTree() {
  const { data } = await deptApi.tree()
  deptTree.value = data
}
onBeforeMount(() => {
  getDeptTree()
})
</script>
<style lang="scss" scoped></style>
